package com.settlement.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.base.IBaseEnum;
import com.settlement.system.common.enums.AmazonStatusEnum;
import com.settlement.system.common.enums.RegisterAmazonStatusEnum;
import com.settlement.system.common.exception.BusinessException;
import com.settlement.system.common.util.HttpUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.controller.AmazonContext;
import com.settlement.system.mapper.SysAmazonMapper;
import com.settlement.system.model.entity.SysAmazon;
import com.settlement.system.model.form.SysAmazonForm;
import com.settlement.system.model.query.SysAmazonQuery;
import com.settlement.system.model.vo.RegisterAmazonVo;
import com.settlement.system.model.vo.SysAmazonImportVo;
import com.settlement.system.service.SysAmazonService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 亚马逊账号表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2024-07-23
 */
@Service
@RequiredArgsConstructor
public class SysAmazonServiceImpl extends ServiceImpl<SysAmazonMapper, SysAmazon> implements SysAmazonService {

    @Value("${system.config.apiKey}")
    private String apiKey;
    @Value("${system.config.service}")
    private String service;
    @Value("${system.config.country}")
    private int country;

    @Override
    public Page<SysAmazon> getPage(SysAmazonQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        Page<SysAmazon> page = new Page<>(pageNum, pageSize);
        Page<SysAmazon> baseMapperPage = this.baseMapper.getPage(page, queryParams);
        for (SysAmazon record : baseMapperPage.getRecords()) {
            record.setStatusName(IBaseEnum.getLabelByValue(record.getStatus(), AmazonStatusEnum.class));
        }
        return baseMapperPage;
    }

    @Override
    public boolean saveSysAmazon(SysAmazonForm sysAmazonForm) {
        SysAmazon sysAmazon = new SysAmazon();
        BeanUtils.copyProperties(sysAmazonForm, sysAmazon);
        sysAmazon.setCreateTime(null);
        return this.saveOrUpdate(sysAmazon);
    }

    @Override
    public SysAmazonForm getSysAmazonFormData(Long id) {
        SysAmazon sysAmazon = this.getById(id);
        SysAmazonForm sysAmazonForm = new SysAmazonForm();
        BeanUtils.copyProperties(sysAmazon, sysAmazonForm);
        return sysAmazonForm;
    }

    @Override
    public boolean deleteSysAmazon(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
    }

    @Override
    public void importData(List<SysAmazonImportVo> voList) {
        List<String> emailList = voList.stream().map(SysAmazonImportVo::getEmail).distinct().toList();
        List<SysAmazon> amazonList = this.list(new LambdaQueryWrapper<SysAmazon>().in(SysAmazon::getEmail, emailList));
        List<String> existEmailList = new ArrayList<>();
        SysAmazon amazon;
        for (String email : emailList) {
            amazon = amazonList.stream().filter(amazon1 -> Objects.equals(email, amazon1.getEmail())).findFirst().orElse(null);
            if(Objects.nonNull(amazon)){
                existEmailList.add(email);
            }
        }
        if(existEmailList.size() > 0){
            throw new BusinessException("以下亚马逊账号已经存在：【%s】".formatted(String.join(",", existEmailList)));
        }
        List<SysAmazon> sysAmazonList = new ArrayList<>();
        for (SysAmazonImportVo importVo : voList) {
            SysAmazon sysAmazon = new SysAmazon();
            sysAmazon.setEmail(importVo.getEmail());
            sysAmazon.setPassword(importVo.getPassword());
            // 状态为注册成功
            sysAmazon.setStatus(AmazonStatusEnum.REGISTERED.getValue());
            sysAmazonList.add(sysAmazon);
        }
        this.saveBatch(sysAmazonList);
    }

    @Override
    public List<SysAmazonImportVo> findByIds(String idsStr) {
        if (!StringUtils.hasText(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysAmazon> sysAmazonList = this.getBaseMapper().selectBatchIds(ids);
        List<SysAmazonImportVo> voList = new ArrayList<>();
        for (SysAmazon sysAmazon : sysAmazonList) {
            SysAmazonImportVo vo = new SysAmazonImportVo();
            BeanUtils.copyProperties(sysAmazon, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public boolean register(String idsStr) {
        if (!StringUtils.hasText(idsStr)) {
            return false;
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysAmazon> sysAmazonList = this.getBaseMapper().selectBatchIds(ids);
        for (SysAmazon amazon : sysAmazonList) {
            Assert.isTrue(Objects.equals(amazon.getStatus(), AmazonStatusEnum.UN_REGISTER.getValue()) || Objects.equals(amazon.getStatus(), AmazonStatusEnum.FAILED.getValue()), "状态不为【待注册】或【注册失败】");
        }
        for (SysAmazon amazon : sysAmazonList) {
            amazon.setStatus(AmazonStatusEnum.REGISTERING.getValue());
        }
        // 添加到任务队列
        String result;
        JSONObject jsonObject;
        String url = "https://api.sms-activate.io/stubs/handler_api.php?api_key=%s&action=getNumberV2&service=%s&country=%s";
        RegisterAmazonVo amazonVo;
        for (SysAmazon amazon : sysAmazonList) {
            amazonVo = new RegisterAmazonVo();
            amazonVo.setEmail(amazon.getEmail());
            amazonVo.setPassword(amazon.getPassword());
            try {
                result = HttpUtils.get(url, apiKey, service, country);
                jsonObject = JSONObject.parseObject(result);
                amazon.setPhone(jsonObject.getString("phoneNumber"));
                amazon.setActivationId(jsonObject.getString("activationId"));
                amazonVo.setStatus(RegisterAmazonStatusEnum.WAITING.getValue());
                AmazonContext.REGISTER_AMAZON_QUEUE.add(amazonVo);
            } catch (Exception e) {
                e.printStackTrace();
                amazon.setStatus(AmazonStatusEnum.FAILED.getValue());
                amazon.setRemark("获取手机号码失败：" + e.getMessage());
            }
        }
        return this.updateBatchById(sysAmazonList);
    }

    @Override
    public boolean updateStatus(List<SysAmazonForm> sysAmazonFormList) {
        List<String> emailList = sysAmazonFormList.stream().map(SysAmazonForm::getEmail).distinct().toList();
        List<SysAmazon> amazons = this.list(new LambdaQueryWrapper<SysAmazon>().in(SysAmazon::getEmail, emailList));
        for (SysAmazon amazon : amazons) {
            amazon.setStatus(AmazonStatusEnum.REGISTERED.getValue());
        }
        return this.updateBatchById(amazons);
    }

    @Override
    public List<SysAmazon> getAmazonMissions() {
        if (AmazonContext.REGISTER_AMAZON_QUEUE.isEmpty()) {
            return new ArrayList<>();
        }
        List<RegisterAmazonVo> amazonVos = new ArrayList<>();
        for (RegisterAmazonVo amazonVo : AmazonContext.REGISTER_AMAZON_QUEUE) {
            amazonVos.add(amazonVo);
            if (amazonVos.size() >= 50) {
                break;
            }
        }
        List<String> emailList = amazonVos.stream().map(RegisterAmazonVo::getEmail).toList();
        return this.list(new LambdaQueryWrapper<SysAmazon>().in(SysAmazon::getEmail, emailList));
    }
}
